#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import logging
import sys
from tqdm import tqdm, trange
import time
import platform
self_filename = os.path.split(sys.argv[0])[1].replace(os.path.splitext(sys.argv[0])[1], "")

logger = None

# logging.DEBUG; logging.INFO; logging.WARNING; logging.ERROR;
def init_logger(level = logging.DEBUG):
    global logger
    if logger is not None:
        return logger
    logger = None
    logger = logging.getLogger()  # 不加名称设置root logger
    level = str(level).lower()

    print(f"log level: {level}")
    if level == 'debug':
        level = logging.DEBUG
    elif level == 'warning':
        level = logging.WARNING
    elif level == 'error':
        level = logging.ERROR
    else:
        level = logging.INFO


    logger.setLevel(level)
    log_dir = "./auto_log"
    if str(platform.system()).lower() == "linux":
        log_dir = "/data/dc-process-log/auto_log"
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    log_path = f'{log_dir}/{self_filename}-({time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())}).log'
    print(f"log path: {log_path}")
    logging_formmater = logging.Formatter(
        '%(asctime)s %(levelname)s (%(filename)s:%(lineno)d) %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S')
    # 使用FileHandler输出到文件
    fh = logging.FileHandler(log_path, mode='w')
    fh.setLevel(level)
    fh.setFormatter(logging_formmater)
    # 使用StreamHandler输出到屏幕
    ch = logging.StreamHandler()
    ch.setStream(tqdm)  # 使得log不会引起进度条冲突：https://stackoverflow.com/a/66906089/7574980
    ch.setLevel(level)
    ch.setFormatter(logging_formmater)
    # 添加两个Handler
    logger.addHandler(ch)
    logger.addHandler(fh)
    return logger